<!--
 * @Description: 单位服务记录-配置产品服务
 * @Author: 马山
 * @Date: 2020-03-30 15:36:26
 * @LastEditTime: 2020-03-30 12:43:55
 * @LastEditors: 马山
 -->


<template>
    
    <el-dialog class="modifyDialog" :close-on-click-modal="false" :visible="isShow" title="配置产品服务" @close="closeDialog" :width="'1000px'">

        <div class="modifyContent">
            <el-row>
                <el-col :span="8">
                    <div class="leftContent">
                        <el-form ref="modifyForm" v-model="unitData" label-position="left" label-width="110px" size="mini" >
                            
                            <div class="title">单位信息：</div>
                            <el-divider></el-divider>

                            <el-form-item label="单位名称：" >
                                <el-input v-model="unitData.unitName"  disabled ></el-input>
                            </el-form-item>
                            <el-form-item label="单位ID："  class="bottom0">
                                <el-input type="text" v-model="unitData.unitId"  disabled></el-input>
                            </el-form-item>
                            <el-form-item label="单位产品名称："  class="bottom0">
                                <el-input type="text" v-model="unitData.unitProductName" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="单位产品编号：" class="bottom0">
                                <el-input type="text" v-model="unitData.unitProductCode" disabled></el-input>
                            </el-form-item>
                            
                            <br>
                            <div class="title">订单信息：</div>
                            <el-divider></el-divider>

                            <el-form-item label="订单编号：" >
                                <el-input type="text" v-model="unitData.orderSn" disabled ></el-input>
                            </el-form-item>
                            <el-form-item label="下单时间：" >
                                <el-date-picker size="mini" disabled
                                    v-model="unitData.orderTimeTemp" format="yyyy-MM-dd HH-mm" 
                                    value-format="timestamp" type="datetime" >
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="订单类型：" class="bottom0">
                                <el-select v-model="unitData.orderType" placeholder="请选择" disabled >
                                    <el-option v-for="item in orderTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-col>
                <el-col :span="16">
                    <div class="rightContent">
                        <div class="title">订单内容</div>
                        <div>
                            <br>
                            <el-tooltip class="item" effect="dark" placement="right">
                                <span slot="content" v-html="content"></span>
                                <el-button type="primary" size="mini" @click="batchSetTime">批量设置生效时间</el-button>
                            </el-tooltip>
                        </div>
                        <el-form label-position="left" label-width="100px">
                            <div v-show="!hasProductData">
                                <el-form-item label="产品：">
                                    <el-input size="mini" v-model="productContent.productName" style="width:150px;" disabled ></el-input>
                                </el-form-item>
                                <!-- 产品包表格 -->
                                <div class="productInfoTable">
                                    <el-table
                                        border
                                        :height="!hasProductData?200:270"
                                        :data="productTable.tableData"
                                        @selection-change="getProductCurrentRow">
                                        <el-table-column
                                            v-for='col in productTable.headData'
                                            :fixed="col.title=='operation' ? 'right':false"
                                            :show-overflow-tooltip=" true "
                                            :width="columnWidth(col)"
                                            :prop="col.title"
                                            :label="col.text"
                                            :key="col.title">
                                            <template slot-scope="scope">
                                                
                                                <!-- 状态 -->
                                                <div v-if="col.title == 'serviceStatus' ">
                                                    <p v-if="scope.row[col.title]=='0'">未生效</p>
                                                    <p v-if="scope.row[col.title]=='1'">生效中</p>
                                                    <p v-if="scope.row[col.title]=='2'">待生效</p>
                                                    <p v-if="scope.row[col.title]=='3'">失效</p>
                                                </div>
                                                <!-- 服务类型 -->
                                                <div v-else-if="col.title == 'serviceType'">
                                                    <p v-if="scope.row[col.title]==0">标准产品</p>
                                                    <p v-if="scope.row[col.title]==1">平台服务</p>
                                                    <p v-if="scope.row[col.title]==2">业务包</p>
                                                    <p v-if="scope.row[col.title]==3">第三方服务</p>
                                                    <p v-if="scope.row[col.title]==4">插件</p>
                                                </div>
                                                <!-- 服务内容 -->
                                                <span v-else-if="col.title == 'serviceContent'">
                                                    <span v-html="scope.row[col.title]"></span>
                                                </span>
                                                <!-- 操作 -->
                                                <div v-else-if="col.title == 'operation' ">
                                                    <!-- 配置产品服务 -->
                                                    <p :class="['viewDetail cursor-pointer',{disabled:scope.row.needConfig=='0'}]" 
                                                        @click="configParamsBtn(scope.$index, scope.row , true )">配置参数</p>
                                                    <p :class="['viewDetail cursor-pointer']" 
                                                        @click="setTakeTimeBtn(scope.$index, scope.row , true)">设置生效时间</p>
                                                </div>
                                                <span v-else>
                                                    <!-- <i class="el-icon-time"></i> -->
                                                    <span>{{ scope.row[col.title] }}</span>
                                                </span>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </div>
                            
                            <el-form-item label="添加服务："></el-form-item>
                            <!-- 服务列表表格 -->
                            <!-- :row-class-name="setRowClassName" -->
                            <div class="serviceTable disabledCheckbox">
                                <el-table
                                    border
                                    ref="serviceTable"
                                    
                                    :height="!hasProductData?200:230"
                                    :data="serviceTable.tableData"
                                    @current-change="handleCurrentChange"
                                    @selection-change="handleSelectionChange"
                                    @select=" ( selection , row ) => selectRowProduct(row)"
                                    @row-click="selectRowProduct"
                                    >
                                    <!-- <el-table-column
                                    type="selection"
                                    label="序号"
                                    width="50">
                                    </el-table-column> -->

                                    <el-table-column
                                        v-for='col in serviceTable.headData'
                                        :fixed="col.title=='operation' ? 'right':false"
                                        :show-overflow-tooltip=" true "
                                        :width="columnWidth(col)"
                                        :prop="col.title"
                                        :label="col.text"
                                        :key="col.title">
                                        <template slot-scope="scope">
                                            
                                            <!-- 状态 -->
                                            <div v-if="col.title == 'serviceStatus' ">
                                                <p v-if="scope.row[col.title]=='0'">未生效</p>
                                                <p v-if="scope.row[col.title]=='1'">生效中</p>
                                                <p v-if="scope.row[col.title]=='2'">待生效</p>
                                                <p v-if="scope.row[col.title]=='3'">失效</p>
                                            </div>
                                            <!-- 服务类型 -->
                                            <div v-else-if="col.title == 'serviceType'">
                                                <p v-if="scope.row[col.title]==0">标准产品</p>
                                                <p v-if="scope.row[col.title]==1">平台服务</p>
                                                <p v-if="scope.row[col.title]==2">业务包</p>
                                                <p v-if="scope.row[col.title]==3">第三方服务</p>
                                                <p v-if="scope.row[col.title]==4">插件</p>
                                            </div>
                                            <!-- 服务内容 -->
                                            <span v-else-if="col.title == 'serviceContent'">
                                                <span v-html="scope.row[col.title]"></span>
                                            </span>
                                            <!-- 操作 -->
                                            <div v-else-if="col.title == 'operation' ">
                                                <!-- 配置产品服务 -->
                                                <p :class="['viewDetail cursor-pointer',{disabled:scope.row.needConfig=='0'}]" 
                                                    @click="configParamsBtn(scope.$index, scope.row , false )">配置参数</p>
                                                <p :class="['viewDetail cursor-pointer']" 
                                                    @click="setTakeTimeBtn(scope.$index, scope.row , false)">设置生效时间</p>
                                            </div>
                                            <span v-else>
                                                <!-- <i class="el-icon-time"></i> -->
                                                <span>{{ scope.row[col.title] }}</span>
                                            </span>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </el-form>
                    </div>
                </el-col>
            </el-row>
        </div>
        
        <div slot="footer" class="dialog-footer">
            <button class="el-button el-button--primary" @click="submit">确 定</button>
            <button class="el-button el-button--info" @click="closeDialog">取 消</button>
        </div>
        
        <!-- 配置参数弹出框 -->
        <ServiceConfigDialog ref="serviceConfigDialog" @submit="changeServiceFun"></ServiceConfigDialog>
        <!-- 设置生效时间弹出框 -->
        <TakeTimeDialog ref="takeTimeDialog" @submit="changeTakeTimeFun"></TakeTimeDialog>

    </el-dialog>

    
</template>

<script>

import ServiceConfigDialog from "./serviceConfigDialog.vue";//配置参数弹出框
import TakeTimeDialog from "./takeTimeDialog.vue"; //设置生效时间弹出框
// import {myBrowser} from "@/utils/tool";
export default{

    name:"modify-dialog",
    components:{
        ServiceConfigDialog,
        TakeTimeDialog
    },
    props:{
        
    },
    data:() =>({
        // myBrowser:myBrowser(),
        content:"对该订单中含有的服务生效时间批量操作，失效时间根据服务内容计算。</br>1、单位产品信息中没有这个服务：这个服务的生效时间T+1，失效时间按照服务内容计算，如果服务方式为「数量」，生效时间、失效时间跟随「平台」；</br>2、单位产品信息中已经有了这个服务：服务的生效时间为 该服务的失效时间 +1，如果服务方式是「数量」，生效时间、失效时间跟随「平台」；",
        isShow:false,
        hasProductData:false,//是否有产品包数据
        //传入的列表数据
        unitData:{
            unitName:"", //单位名称
            unitId:"",   //单位ID
            unitProductCode:"", //单位产品编号
            unitProductName:"", //单位产品名称
            orderSn:"", //订单编号
            orderType:"1", //订单类型
            orderTime:"", //下单时间
        },
        // 订单类型列表数据
        orderTypeOptions:[
            {
                value:"1",
                label:"正式"
            },{
                value:"2",
                label:"试用"
            }
        ],
        productContent:{ //产品信息
            orderAggregateId:"",
            productName:""
        },
        //产品明细表-主产品
        productTable:{
            currentRow:"",//当前行数据
            headData:[
                {
                    title:"serviceType",
                    text:"服务类型"
                },{
                    title:"serviceName",
                    text:"服务名称"
                },{
                    title:"serviceMode", 
                    text:"服务方式"
                },{
                    title:"serviceContent",
                    text:"服务内容"
                },{
                    title:"serviceStatus",
                    text:"状态"
                },{
                    title:"beginDate",
                    text:"生效时间"
                },{
                    title:"expireDate",
                    text:"失效时间"
                },{
                    title:"operation",
                    text:"操作"
                }
            ],
            tableData:[]
        },
        //附加购买服务表格数据-子产品
        serviceTable:{
            markRowSelect:{},//记录单选
            currentRow:"",//当前行数据
            headData:[
                {
                    title:"serviceType",
                    text:"服务类型"
                },{
                    title:"serviceName",
                    text:"服务名称"
                },{
                    title:"serviceMode", 
                    text:"服务方式"
                },{
                    title:"serviceContent",
                    text:"服务内容"
                },{
                    title:"serviceStatus",
                    text:"状态"
                },{
                    title:"beginDate",
                    text:"生效时间"
                },{
                    title:"expireDate",
                    text:"失效时间"
                },{
                    title:"operation",
                    text:"操作"
                }
            ],
            tableData:[
                // {
                //     "typeDescription":"",
                //     "serviceName":"固定资产管理",
                //     "serviceMode":{
                //         count:"1000",time:24
                //     },
                //     "serviceContent":{
                //         count:"1000",time:24
                //     },
                //     "operation":""
                // }
            ]
        },
    }),
    created(){},
    mounted(){},
    methods:{

        open(data){
            this.isShow = true;
            
            // let configData = Object.assign({},data);
            let configData = JSON.parse(JSON.stringify(data));
            this.unitData = configData.unitData;
            
            let orderTime = configData.unitData.orderTime;
            if(orderTime){
                let formatTime = new Date(orderTime).getTime();
                this.unitData.orderTime = formatTime;
                // this.unitData.orderTime = orderTime ? this.formatTime(orderTime):"";
            }
            this.getOrderDetail();
        },

        // 获取订单总数据
        getOrderDetail(){
            if(!this.unitData.orderSn)return;//修改的时候才会走查询接口
            this.api.configOrderUnitList({ //获取租户产品配置信息
                orderSn:this.unitData.orderSn
            }).then( res =>{
                console.log(res);
                let listData = res.data;
                if(!listData || !(listData instanceof Object) )return;
                this.productContent.productName = listData.mainUnitProductName;//主产品名称
                this.productContent.orderAggregateId = listData.orderAggregateId;//
                let products = listData.products;//产品包表
                let additionalProducts = listData.additionalProducts;//附加服务表
                //产品明细表:
                this.productTable.tableData = [];
                this.serviceTable.tableData = [];
                products.forEach( item =>{
                    let obj = {
                        dependId:item.dependId,
                        orderProductId:item.orderProductId,
                        orderAggregateId:item.orderAggregateId,
                        serviceType:item.type,   //服务类型
                        serviceName:item.serviceName,   //服务名称
                        serviceStatus:item.status,  //状态
                        serviceMode:item.serviceModeType,
                        serviceContent:item.serviceContent,
                        beginDate:this.formatTime(item.beginDate),  //生效时间
                        expireDate:this.formatTime(item.expireDate), //失效时间
                        needConfig:item.needConfig,
                        beginDateTamp:item.beginDate, //记录下时间戳
                        expireDateTamp:item.expireDate,
                    };
                    this.productTable.tableData.push(obj);
                });
                //有产品包数据，便隐藏产品整个容器
                !products || products.length==0 && (this.hasProductData = true); 
                // 附加服务表：
                additionalProducts.forEach( item =>{
                    let obj = {
                        dependId:item.dependId,
                        orderProductId:item.orderProductId,
                        orderAggregateId:item.orderAggregateId,
                        serviceType:item.type,   //服务类型
                        serviceName:item.serviceName,   //服务名称
                        serviceStatus:item.status,  //状态
                        serviceMode:item.serviceModeType,
                        serviceContent:item.serviceContent,
                        beginDate:this.formatTime(item.beginDate),  //生效时间
                        expireDate:this.formatTime(item.expireDate), //失效时间
                        needConfig:item.needConfig,
                        beginDateTamp:item.beginDate, //记录下时间戳
                        expireDateTamp:item.expireDate,
                    };
                    this.serviceTable.tableData.push(obj);
                });
            }).catch( err =>{
                console.log(err);
                this.productContent.productName = "";//租户订购主产品-单位产品名称
                this.productTable.tableData = [];
                this.serviceTable.tableData = [];

            });
        },
        
        // 配置参数按钮
        configParamsBtn(index , row , isProduct){
            if(row.needConfig == '0')return;
            let data = {
                isProduct:isProduct,
                row:row,
                index:index
            }
            this.$refs.serviceConfigDialog.open(data);
        },
        //监听配置参数回调
        changeServiceFun(data){
            console.log(data);
            let currentIndex = data.currentIndex;
            let configData = data.configData;
            if(data.isProduct){ //产品表回调
                this.productTable.tableData[currentIndex].configData = configData;
            }else{ //附加服务表回调
                this.serviceTable.tableData[currentIndex].configData = configData;
            }
            

        },
        //设置生效时间
        setTakeTimeBtn(index ,row , isProduct ){
            let data = {
                isProduct:isProduct,
                row:row,
                index:index
            }
            this.$refs.takeTimeDialog.open(data);
        },
        //监听设置生效时间回调
        changeTakeTimeFun(data){
            let currentIndex = data.currentIndex;
            let beginDate = data.beginDate;
            if(!beginDate)return;
            let productsId={};
            this.productTable.tableData && this.productTable.tableData.forEach( item =>{
                if(item.orderProductId == data.orderProductId){
                    productsId[item.orderProductId] = data.beginDateTamp;
                }else{
                    productsId[item.orderProductId] = item.beginDateTamp||"";
                }
            });
            this.serviceTable.tableData && this.serviceTable.tableData.forEach( item =>{
                if(item.orderProductId == data.orderProductId){
                    productsId[item.orderProductId] = data.beginDateTamp;
                }else{
                    productsId[item.orderProductId] = item.beginDateTamp||"";
                }
            });
            this.api.calBeginDate({
                orderSn:this.unitData.orderSn,
                orderAggregateId:data.orderAggregateId,
                pageSetBeginDate:{
                    ...productsId
                },
                orderProductId:data.orderProductId,
                beginDate:beginDate
            }).then( res =>{
                console.log(res);
                this.setTimeFormat(res);
            }).catch( err =>{
                console.log(err);
            });
            
        },
        //批量设置生效时间
        batchSetTime(){

            this.api.batchCalBeginDate({
                orderSn:this.unitData.orderSn,
                orderAggregateId:this.productContent.orderAggregateId //订单编号
            }).then( res =>{
                console.log(res);
                this.setTimeFormat(res);
            }).catch( err =>{
                console.log(err);

            });
        },
        // 批量设置时间和单独设置时间公共设置
        setTimeFormat(res){
            let listData = res.data.calRet;
            let self = this;
            let callData = function (){
                //产品表
                self.productTable.tableData && self.productTable.tableData.forEach( item =>{
                    Object.entries(listData).forEach( cell =>{
                        let key = cell[0],value=cell[1];
                        if( (key == item.orderProductId) && value){
                            item.beginDate = self.formatTime(value.beginDate);
                            item.expireDate = self.formatTime(value.expireDate);
                            item.beginDateTamp = value.beginDate;
                            item.expireDateTamp = value.expireDate;
                        }
                    });
                });
                //服务表
                self.serviceTable.tableData && self.serviceTable.tableData.forEach( item =>{
                    Object.entries(listData).forEach( cell =>{
                        let key = cell[0],value=cell[1];
                        if( (key == item.orderProductId) && value){
                            item.beginDate = self.formatTime(value.beginDate);
                            item.expireDate = self.formatTime(value.expireDate);
                            item.beginDateTamp = value.beginDate;
                            item.expireDateTamp = value.expireDate;
                        }
                    });
                });
            }
            if(res.data.message){
                this.$confirm(res.data.message, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                   callData();
                });
            }else{
                callData();
            }
        },
        //提交保存
        submit(){
            // 提取两个表格里的数据
            let dataArray = [];
            // 产品明细表：
            this.productTable.tableData && this.productTable.tableData.forEach( item =>{
                let obj = {
                    orderProductId:item.orderProductId,
                    beginDate:item.beginDateTamp,
                    expireDate:item.expireDateTamp,
                    needConfig:item.needConfig,
                    serviceParameters:item.configData?[...item.configData]:null
                }
                dataArray.push(obj);
            });
            // 附加服务表：
            this.serviceTable.tableData && this.serviceTable.tableData.forEach( item =>{
                let obj = {
                    orderProductId:item.orderProductId,
                    beginDate:item.beginDateTamp,
                    expireDate:item.expireDateTamp,
                    needConfig:item.needConfig,
                    serviceParameters:item.configData?[...item.configData]:null
                }
                dataArray.push(obj);
            });
            this.api.configServiceParameters(
                [...dataArray],{loading:true}
            ).then(res =>{
                console.log(res);
                this.$message("保存成功!");
                this.$emit("submit",res);
                this.closeDialog();
            }).catch( err =>{
                console.log(err);
            });
        },



        //附加服务表，增加行索引
        setRowClassName({row, column, rowIndex, columnIndex}){
            row.currentIndex = rowIndex; //手动给每个行设置一个索引
        },

        

        
        // 表单校验
        checkFrom(){
            this.$refs.modifyForm.validate((valid) => {
                if (valid) {
                    return true;
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
            // this.$refs.modifyForm.resetFields(); //重置
        },

        // 表格数据进行一次格式处理
        tableDataFormat(item){
            let parameter = item.parameter;
            let obj = {
                serviceMode:"",
                serviceContent:"",
            }
            if(parameter.serviceMode){
                obj.serviceMode = {
                    count:parameter.serviceMode.count,
                    time:parameter.serviceMode.time
                }
            }
            if(parameter.serviceContent && (parameter.serviceContent instanceof Object)){
                obj.serviceContent = {
                    count:parameter.serviceContent.count,
                    time:parameter.serviceContent.time
                }
            }else{
                obj.serviceContent = parameter.serviceContent;
            }
            return obj;
        },
        //获得当前产品明细表行数据
        getProductCurrentRow(val){
            this.productTable.currentRow = val;
        },
        //获得当前附加服务表行数据
        handleSelectionChange(val){
            // this.serviceTable.currentRow = val;
        },
        // 单选
        selectRowProduct(row) {
            let markRowSelect = this.serviceTable.markRowSelect;
            this.$refs.serviceTable.clearSelection();
            if ( markRowSelect && markRowSelect.orderProductId && markRowSelect.orderProductId === row.orderProductId ) {
                markRowSelect = {};
                this.$refs.serviceTable.setCurrentRow();
            } else {
                markRowSelect = row;
                this.$refs.serviceTable.setCurrentRow(row);
                this.$refs.serviceTable.toggleRowSelection(row);
            }
        },
        // 在单选框的change事件中高亮选中行
        handleCurrentChange(row) {
            this.$refs.serviceTable.clearSelection();
            this.$refs.serviceTable.toggleRowSelection(row);
            this.serviceTable.currentRow = row;
        },
        closeDialog(){
            this.hasProductData = false;
            this.productContent.productName = ""; //当前产品包
            this.productTable.tableData = []; //产品包明细表
            this.serviceTable.tableData = []; //附加服务表
            this.isShow = false;

        },
        formatNumber (n){
            n = n.toString()
            return n[1] ? n : '0' + n
        },
        // 时间格式化
        formatTime(date){
            if(!date)return;
            date = new Date(JSON.parse(date));
            let year = date.getFullYear()
            let month = date.getMonth() + 1
            let day = date.getDate()
            let hour = date.getHours()
            let minute = date.getMinutes()
            let second = date.getSeconds();
            return [year, month, day].map(this.formatNumber).join('-') + ' ' + [hour, minute, second].map(this.formatNumber).join(':')
        },
        //手动设置一下列宽
        columnWidth(col){
            let mainContentW = document.body.offsetWidth - 200;
            let width = 50;
            switch (col.title){
                case "operation":
                    width = 105;
                    break;
                default :
                    width = "100%";
                    break;
            }
            return width;
        },
    }

    

}



</script>

<style lang="scss" scoped>

.modifyDialog{
    .title{
        color: #324558;
        font-weight: 600;
    }
    .el-divider--horizontal{
        margin: 10px 0;
    }
    .leftContent{
        padding: 12px 14px 12px 20px;
    }
    .rightContent{
        background-color: #EDF0F6;
        padding: 12px 14px 12px 10px;
    }
    .selectTanantBtn{
        color: #768592;
    }
    .viewDetail{
        text-decoration: underline;
        color: #409EFF;
        &.disabled{
            color: #ccc;
        }
    }
    .select_text,.delete_text{
        color: #409EFF; 
        font-size: 12px;
        margin-left: 24px;
    }
    .select_text.disabled,.delete_text.disabled{
        color: #ccc!important;
    }
    .delete_text{
        padding-right: 12px;
    }
    .el-dialog{
        // width:380px;
        .el-dialog__body{
            .el-form-item{
                margin-bottom:5px;
                &.bottom0{
                  margin-bottom:3px;  
                }
            }
        }
    }
    .el-input,.el-textarea{
        width:100%;
        font-size: 12px;
        .el-textarea__inner{
            min-height: 50px;
        }
    }
    .el-select{
        // width:228px;
        font-size: 12px;
    }
    .el-select>.el-input{
        width:100%!important;
        font-size: 12px;
    }
    .el-button.is-disabled{
        color: #C0C4CC!important;
        border-color: #EBEEF5!important;
    }

}

</style>


